<template>
  <div class="card">
    <el-button type="primary" :icon="CirclePlus" @click="addRole">新增角色</el-button>

    <div style="margin-top: 20px">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="role_id" label="角色标识" width="180" />
        <el-table-column prop="role_name" label="角色名称" width="180" />
        <el-table-column prop="comment" label="角色备注" show-overflow-tooltip />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :icon="Setting"
              @click="assignMenu(row)"
            >
              分配菜单
            </el-button>
            <el-button size="small" type="warning" :icon="EditPen" @click="editRole(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="removeRole(row)">
              删除
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </div>

    <div style="margin-top: 20px; display: flex; justify-content: center">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 角色弹窗组件 -->
    <RoleDialog
      v-model:visible="dialogVisible"
      :treeParent="treeParent"
      :type="dialogType"
      :roleData="currentRole"
      @success="handleDialogSuccess"
      @cancel="handleDialogCancel"
    />

    <!-- 分配菜单 -->
    <AssignMenus
      ref="assignMenuRef"
      :treeParent="treeParent"
      :roleData="currentRole"
      @confirm="assignConfirm"
      @cancel="assignCancel"
    />
  </div>
</template>

<script setup lang="ts" name="roleManage">
import { onMounted, ref } from 'vue'
import { getRoleListApi, addRoleApi } from '@/api/modules/role'
import { CirclePlus, Delete, EditPen, Setting } from '@element-plus/icons-vue'
import RoleDialog from './components/RoleDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenuTreeParentApi } from '@/api/modules/menu'
import { MenuApi } from '@/api/interface/menu'
import AssignMenus from './components/AssignMenus.vue'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const treeParent = ref<MenuApi.Menu[]>([])
const selectMenus = ref([])
const assignMenuRef = ref()

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentRole = ref({})

onMounted(() => {
  getRoleList()
  getMenuTreeParent()
})

const getRoleList = async () => {
  loading.value = true
  try {
    let res: any = await getRoleListApi({
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.errCode === 0) {
      tableData.value = res.data || []
      total.value = res.count || 0
    } else {
      ElMessage.error(res.errMsg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const getMenuTreeParent = async () => {
  let res: any = await getMenuTreeParentApi()
  if (res.errCode === 0) {
    treeParent.value = res.data
  }
}

// 新增角色
const addRole = () => {
  currentRole.value = {} // 清空当前角色数据
  dialogVisible.value = true
  dialogType.value = 'add'
}

// 分配菜单
const assignMenu = (row) => {
  currentRole.value = { ...row }
  assignMenuRef.value?.showDialog()
}
const assignConfirm = () => {
  currentRole.value = {}
  getRoleList()
}
const assignCancel = () => {
  currentRole.value = {}
}

// 编辑角色
const editRole = (row) => {
  currentRole.value = { ...row }
  dialogVisible.value = true
  dialogType.value = 'edit'
}

// 删除角色
const removeRole = (row) => {
  currentRole.value = { ...row }
  dialogVisible.value = true
  dialogType.value = 'delete'
}

// 弹窗成功回调
const handleDialogSuccess = (data) => {
  if (data.isDeleted) {
    ElMessage.success(`角色 "${data.role_name}" 已成功删除`)
  } else if (data.isNew) {
    ElMessage.success(`角色 "${data.role_name}" 已成功创建`)
  } else {
    ElMessage.success(`角色 "${data.role_name}" 已成功更新`)
  }

  // 刷新列表
  getRoleList()
}

// 弹窗取消回调
const handleDialogCancel = () => {
  // 可以在这里做一些额外的处理
  console.log('操作已取消')
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getRoleList() // 切换页码时重新获取数据
}
</script>

<style lang="scss" scoped>
.card {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
